package com.sunshine.lnuplus.model

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.os.Looper
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.cardview.widget.CardView
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.model.room.TimetableRepository
import com.sunshine.lnuplus.utils.ColorUtils
import com.sunshine.lnuplus.utils.DateUtils
import com.sunshine.lnuplus.utils.LessonUtils
import com.sunshine.lnuplus.view.LessonLayout
import java.util.*
import kotlin.collections.ArrayList

/**
 * Created by sunshine on 2020/3/14
 */

class WidgetData {
    companion object{
        var widgetStyle: LessonStyle? = null
        var lessonList: ArrayList<LessonBean>? = null
        var dayBitmap: Bitmap? = null
        var lessonBitmap: Bitmap? = null

        fun initData(context: Context?) {
            val sharedPreferences = context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE)
            val count = sharedPreferences.getInt("every_day_count", 5)
            val dateHeight = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                50f,
                context.resources.displayMetrics
            ).toInt()
            val heightDistant = sharedPreferences.getInt("widget_height_distant", 10)
            widgetStyle = LessonStyle(
                weekCount = sharedPreferences.getInt("weeks_count", 30),
                height = sharedPreferences.getInt("widget_height", 150),
                textSize = sharedPreferences.getInt("widget_text_size", 10),
                textColor = sharedPreferences.getString("widget_text_color", "#FFFFFF")!!,
                showWeekend = sharedPreferences.getBoolean("widget_show_weekend", true),
                widthDistant = sharedPreferences.getInt("widget_width_distant", 5),
                heightDistant = heightDistant,
                count = count,
                round = sharedPreferences.getInt("widget_radius", 30),
                showTeacher = sharedPreferences.getBoolean("widget_show_teacher", true),
                padding = sharedPreferences.getInt("widget_padding", 5),
                alpha = sharedPreferences.getInt("widget_alpha", 200),
                showTime = sharedPreferences.getBoolean("widget_show_time", true),
                timeTextSize = sharedPreferences.getInt("widget_time_text_size", 10),
                lessonTime = sharedPreferences.getString("lesson_time","8:00\n9:50|10:10\n12:00|13:30\n15:20|15:40\n17:30|18:00\n19:50")!!.split("|") as ArrayList<String>,
                dateColor = sharedPreferences.getString("widget_date_color", "#D81B60")!!,
                dateAndTimeTextColor = sharedPreferences.getString("widget_date_and_time_text_color", "#FFFFFF")!!,
                showNotInThisWeek = sharedPreferences.getBoolean("widget_show_not_in_this_week", true),
                startMonth = sharedPreferences.getInt("start_month", if(DateUtils.month > 8) 8 else 2),
                startDay = sharedPreferences.getInt("start_day", 2),
                detailShowNotInThisWeek = sharedPreferences.getBoolean("detail_show_not_in_this_week", true),
                sundayFirst = sharedPreferences.getBoolean("widget_sunday_first", false),
                calenderMode = sharedPreferences.getBoolean("calender_mode", false),
                textLeft = sharedPreferences.getBoolean("text_left", true),
                nextDay = sharedPreferences.getBoolean("widget_next_day", false),
                nextDayTime = sharedPreferences.getInt("widget_next_day_time", 21)
            )

            val repository = TimetableRepository(context)
            LessonUtils.initLessonBean(repository.getLesson(), null, null, null)
            lessonList = InitData.lessonList
            println(lessonList)

        }

        fun initDayView(context: Context) {
            val view = LayoutInflater.from(context).inflate(R.layout.view_widget_day, null)
            val height = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                75f,
                context.resources.displayMetrics
            ).toInt()
            val container = view.findViewById<LinearLayout>(R.id.widget_day_layout)
            var today = DateUtils.getTodayOfWeek()
            var thisWeek = DateUtils.getThisWeek(widgetStyle!!.startMonth, widgetStyle!!.startDay)
            if(widgetStyle!!.nextDay && widgetStyle!!.nextDayTime <= DateUtils.hour){
                if (DateUtils.getTodayOfWeek() == 7){
                    today = 1
                    thisWeek = DateUtils.getThisWeek(widgetStyle!!.startMonth, widgetStyle!!.startDay) + 1
                }else{
                    today = DateUtils.getTodayOfWeek() + 1
                }
            }
            val lessonList = ArrayList<View>()
            ColorUtils.init(context)

            WidgetData.lessonList?.forEach {
                if(it.dayOfWeek == today){
                    if(it.weeks.contains(thisWeek)){
                        println(it)
                        //不加false会报错
                        val itemView = LayoutInflater.from(context).inflate(R.layout.item_day, container, false)
                        itemView.findViewById<CardView>(R.id.day_cardview).setCardBackgroundColor(
                            ColorUtils.setBackgroundColor(it.lessonName))
                        itemView.findViewById<TextView>(R.id.lesson_name).text = it.lessonName
                        initDayItemView(itemView, it)
                        lessonList.add(itemView)
                    }else if(widgetStyle!!.showNotInThisWeek){
                        val itemView = LayoutInflater.from(context).inflate(R.layout.item_day, container, false)
                        itemView.findViewById<CardView>(R.id.day_cardview).setCardBackgroundColor(Color.GRAY)
                        itemView.findViewById<TextView>(R.id.lesson_name).text = "${it.lessonName}（非本周）"
                        initDayItemView(itemView, it)
                        lessonList.add(itemView)
                    }
                }
            }
            Collections.sort(lessonList, StartComparable())
            lessonList.forEach {
                container.addView(it)
            }

            val measuredWidth = View.MeasureSpec.makeMeasureSpec(1000, View.MeasureSpec.EXACTLY)
            val measuredHeight = View.MeasureSpec.makeMeasureSpec(if(height * lessonList.size == 0) 1 else height * lessonList.size, View.MeasureSpec.EXACTLY)
            view.measure(measuredWidth, measuredHeight)
            view.layout(0, 0, view.measuredWidth, view.measuredHeight)

            val bitmap = Bitmap.createBitmap(1000, if(height * lessonList.size == 0) 1 else height * lessonList.size, Bitmap.Config.ARGB_8888)
            val c= Canvas(bitmap)
            view.draw(c)
            dayBitmap = bitmap
        }

        private fun initDayItemView(itemView: View, lessonBean: LessonBean){
            itemView.findViewById<TextView>(R.id.time).text = "第${lessonBean.start}节\n第${lessonBean.end}节"
            itemView.findViewById<TextView>(R.id.info).text = "地点：${lessonBean.location} 老师：${lessonBean.teacher}"
            itemView.findViewById<TextView>(R.id.textView_jie).text = "${lessonBean.start}" //记录当前节数用于排序
        }

        fun initTimetableView(context: Context) {
            val view = LayoutInflater.from(context).inflate(R.layout.view_widget_timetable, null)
            val dateHeight = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                50f,
                context.resources.displayMetrics
            ).toInt()
            val height = widgetStyle!!.height * widgetStyle!!.count + widgetStyle!!.heightDistant * (widgetStyle!!.count + 1) + dateHeight + 100

            view.findViewById<LessonLayout>(R.id.lesson_layout).init(
                lessonList = lessonList!!,
                lessonStyle = widgetStyle!!,
                thisWeek = DateUtils.getThisWeek(widgetStyle!!.startMonth, widgetStyle!!.startDay),
                otherWeek = DateUtils.getThisWeek(widgetStyle!!.startMonth, widgetStyle!!.startDay),
                fragmentManager = null,
                isSetting = false,
                fragment = null,
                adapter = null
            )
            val measuredWidth = View.MeasureSpec.makeMeasureSpec(1000, View.MeasureSpec.EXACTLY)
            val measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
            view.measure(measuredWidth, measuredHeight)
            view.layout(0, 0, view.measuredWidth, view.measuredHeight)
            val bitmap = Bitmap.createBitmap(1000, height, Bitmap.Config.ARGB_8888)
            val c= Canvas(bitmap)
            view.draw(c)
            lessonBitmap = bitmap
        }
    }
}

class StartComparable : Comparator<View>{
    override fun compare(o1: View?, o2: View?): Int {
        return (o1!!.findViewById<TextView>(R.id.textView_jie).text.toString().toInt()).compareTo((o2!!.findViewById<TextView>(R.id.textView_jie).text.toString().toInt()))
    }
}